<script setup lang="ts">
import { ref, reactive, computed, provide } from "vue"
import { ElMessageBox } from "element-plus"
import dayjs from 'dayjs';
import { getCertifiedWhiteDetailApi, delCertifiedWhiteApi } from "#/api/certificate/white-link"
import { obsDownload } from "#/utils/obs"

import EditCertifiDialog from './edit-certifi-dialog.vue';
import PreviewCertifiDialog from './preview-certifi-dialog.vue';
import EditWhiteLinkDialog from './edit-white-link-dialog.vue';
import CustomPopover from '#/components/custom-popover.vue';

import PdfDialog from './pdf-dialog.vue';
import { Trash2, Pencil, Eye } from '@vben/icons';
import { $t } from '@vben/locales';

const editCertifiDialogRef = ref<InstanceType<typeof EditCertifiDialog> | null>(null);
const previewCertifiDialogRef = ref<InstanceType<typeof PreviewCertifiDialog> | null>(null);
const editWhiteLinkDialogRef = ref<InstanceType<typeof EditWhiteLinkDialog> | null>(null);
const pdfDialogRef = ref<InstanceType<typeof PdfDialog> | null>(null);

defineOptions({ name: 'Dialog' })
const props = defineProps({
  certifiList: {
    type: Array as any,
    required: true
  }
});

const emit = defineEmits(['queryTable'])
const dialogVisible = ref(false)
const loading = ref(false)
const tableData = ref()
const detailDefault = {
  certified: <any>([]),
  createTime: null,
  email: '',
  id: '',
  idCard: null,
  name: '',
  phone: '',
  userId: ''
}
const detailData = reactive({ ...detailDefault })

provide('certifiDetail', {
  getCertifiName: (id: any) => {
    if (props.certifiList) {
      return detailData?.certified?.find((_: { certificationId: any, certificationName: any }) => id === _.certificationId)?.certificationName
    } else {
      return '--'
    }
  }
});

const getFormatTime = computed(() => {
  return (time: any) => {
    return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '--'
  }
})

const editCert = (data: any) => {
  editCertifiDialogRef.value?.inint({ ...data, name: detailData.name })
}

const addCert = () => {
  editWhiteLinkDialogRef.value?.inint(detailData)
}

const inint = (data: any = null) => {
  Object.assign(detailData, data)
  dialogVisible.value = true
  getCertiList()
}

const getCertiList = () => {
  let params = {
    userId: detailData.userId
  }
  loading.value = true
  getCertifiedWhiteDetailApi(params).then(res => {
    let { data } = res;
    tableData.value = data
  }).finally(() => {
    loading.value = false
  })
}

const getCertiName = computed(() => {
  return (id: any) => {
    if (props.certifiList) {
      return props.certifiList?.find((_: { id: any, name: any }) => id === _.id)?.name || '--'
    } else {
      return '--'
    }
  }
})


// 证书预览
const previewCerti = (data: any) => {
  previewCertifiDialogRef.value?.inint(data)
}
// 更新
const updateTable = () => {
  emit('queryTable')
  getCertiList()
}
const deleteCert = (data: any) => {
  console.log(data)
  ElMessageBox.confirm(
    $t('certificate.deleteConfirm'),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      let params = { id: data.id }
      loading.value = true
      delCertifiedWhiteApi(params).then(() => {
        emit('queryTable')
        getCertiList()
      }).finally(() => {
        loading.value = false
      })
    })
    .catch(() => { })
}

const checkCertificate = async (data: any) => {
  obsDownload({
    Bucket: import.meta.env.VITE_OBS_BUCKET,
    Key: data.certificate,
    // SaveByType: 'file'
  }, (err: any, result: any) => {
    if (err) {
      console.error('获取PDF失败:', err);
      return;
    }
    console.log(result)
    const url = result.InterfaceResult.Content;
    pdfDialogRef.value?.inint({ url, path: data.certificate, fileName: data.certificateNumber })
  })
}

const handleClose = () => {
  dialogVisible.value = false
  tableData.value = []
}

defineExpose({ inint })

</script>
<template>
  <el-drawer :destroy-on-close="true" :close-on-click-modal="false" @close="handleClose" :close-on-press-escape="false"
    :append-to-body="true" class="detail-war" size="80%" v-model="dialogVisible" direction="rtl">
    <template #header>
      <h4 class="detail-title text-black font-bold">{{ $t('common.detailTxt') }}</h4>
    </template>
    <template #default>
      <div class="flex h-full flex-col">
        <div class="user-info mb-[24px]">
          <div class="font-bold mb-[15px] text-[#191919] text-[14px]">{{ $t('common.infoTxt') }}</div>
          <div class="flex flex-wrap">
            <div class="info-item leading-[22px] text-[#191919] text-[14px] mb-[16px]"><span
                class="inline-block w-[100px] text-right text-[#595959] mr-[10px]">{{ $t('whiteLink.memberNameTxt') }}</span>{{ detailData.name ?? '--'
                }}</div>
            <div class="info-item leading-[22px] text-[#191919] text-[14px] mb-[16px]"><span
                class="inline-block w-[100px] text-right text-[#595959] mr-[10px]">{{ $t('common.phoneTxt') }}</span>{{ detailData.phone ??
                  '--' }}</div>
            <div class="info-item leading-[22px] text-[#191919] text-[14px] mb-[16px]"><span
                class="inline-block w-[100px] text-right text-[#595959] mr-[10px]">{{ $t('common.idCardTxt') }}</span>{{ detailData.idCard ??
                  '--' }}</div>
            <div class="info-item leading-[22px] text-[#191919] text-[14px] mb-[16px]"><span
                class="inline-block w-[100px] text-right text-[#595959] mr-[10px]">{{ $t('common.emailTxt') }}</span>{{ detailData.email ?? '--'
                }}</div>
            <div class="info-item leading-[22px] text-[#191919] text-[14px]"><span
                class="inline-block w-[100px] text-right text-[#595959] mr-[10px]">{{ $t('common.createTimeTxt') }}</span>{{
                  getFormatTime(detailData.createTime) ?? '--' }}</div>
          </div>
        </div>
        <h4 class="font-bold leading-[100%]">{{ $t('whiteLink.certifiedInfoTxt') }} </h4>
        <div class="pt-[16px] pb-[12px]">
          <el-button type="primary" @click="addCert">{{ $t('common.newTxt') }}</el-button>
        </div>
        <div class="flex-1 overflow-auto pt-[10px]">
          <el-table v-loading="loading" height="100%" :data="tableData"
            class="min-h-[1px] flex-1 bg-[#fff] overflow-auto">
            <el-table-column align="center" width="60px" type="index" :label="$t('common.numberIdxTxt')" />
            <el-table-column min-width="250" prop="className" :label="$t('whiteLink.certifiedNameTxt')">
              <template #default="{ row }">
                <CustomPopover :strTxt="getCertiName(row.certifiedId)"></CustomPopover>
              </template>
            </el-table-column>
            <el-table-column min-width="230" :label="$t('whiteLink.buyTimeTxt')">
              <template #default="{ row }">
                <div>{{ getFormatTime(row.createTime) }}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="examTakeTime" min-width="230" :label="$t('whiteLink.examTakeTimeTxt')">
              <template #default="{ row }">
                <div>{{ getFormatTime(row.examTakeTime) }}</div>
              </template>
            </el-table-column>
            <el-table-column min-width="80" :label="$t('whiteLink.scoreTxt')">
              <template #default="{ row }">
                <div>
                  {{ row.score ?? '--' }}
                </div>
              </template>
            </el-table-column> -->
            <el-table-column min-width="50" fixed="right" :label="$t('common.operationTxt')">
              <template #default="{ row }">
                <!-- <el-tooltip effect="dark" :content="$t('common.viewTxt')" :show-after="1000" placement="top">
                  <el-button :disabled="!row.certificate" link size="small" @click="checkCertificate(row)" :icon="Eye"></el-button>
                </el-tooltip> -->
                <el-tooltip effect="dark" :content="$t('common.deleteTxt')" :show-after="1000" placement="top">
                  <el-button link @click="deleteCert(row)" :icon="Trash2">
                  </el-button>
                </el-tooltip>
                <!-- <el-tooltip effect="dark" :content="$t('common.editTxt')" :show-after="1000" placement="top">
                  <el-button link @click="editCert(row)" :icon="Pencil">
                  </el-button>
                </el-tooltip> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{$t('common.cancelTxt')}}
        </el-button>
        <el-button type="primary" @click="handleClose">
          {{$t('common.submitTxt')}}
        </el-button>
      </div>
    </template>
  </el-drawer>
  <EditCertifiDialog ref="editCertifiDialogRef" @update-table="updateTable" @preview-certi="previewCerti">
  </EditCertifiDialog>
  <PreviewCertifiDialog ref="previewCertifiDialogRef"></PreviewCertifiDialog>
  <EditWhiteLinkDialog ref="editWhiteLinkDialogRef" @query-table="updateTable"></EditWhiteLinkDialog>
  <PdfDialog ref="pdfDialogRef"></PdfDialog>
</template>
<style lang="less" scoped>
.detail-war {
  .info-item {
    flex: 50%;
    width: calc(100% - 20px) / 2;
  }
}
</style>
